//
//  UnUnBindPlatformBottomAlertView.swift
//  LeTu
//
//  Created by g1 on 2024/1/7.
//

import UIKit

class UnBindPlatformBottomAlertView: UIView {

    private var platformType = PayPlatformType.wechat
    
    private let rootView = UIApplication.shared.keyWindow!
    private var backgroundView: UIView = UIView()
    
    private var panPositionY: CGFloat = 0
    private var panStartPositionY: CGFloat = 0
    
    var toUnBindHandle: ((PayPlatformType) -> Void)?
    
    init(platformType: PayPlatformType) {
        super.init(frame: .zero)
        
        self.platformType = platformType
        
        configUI()
            
        titleLabel.text = "已绑定账号".localized
        conformBtn.setTitle("解除\(platformType.getName())绑定".localized)
        promptLabel.attributed.text = "\("温馨提示：半年内只能换绑一次，一个\(platformType.getName().localized)账号只能绑定一个本App账号", .kern(0.8))"
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        DispatchQueue.main.async {
            self.lineView.layerCornerRadius(2.5)
            self.backView.layerCornerRadius(16, [.topLeft,.topRight])
            self.conformBtn.layerCornerRadius(self.conformBtn.height/2)
        }
    }
    private func getHieght() -> CGFloat {
        return 318 + CGFloat.app_btnHeight + (iPhoneX ? Size.safeAreaBottomGap:20)
    }
    
    // MARK: - UIButtonAction
    @objc func confromBtnAction() {
        guard let handle = toUnBindHandle else { return }
        hide()
        handle(platformType)
    }
    
    // MARK: - configUI
    func configUI() {
        
        // 防止多个 AlertView 重复显示
        if rootView.subviews.filter({ $0.isKind(of: UnBindPlatformBottomAlertView.self) }).count > 0 { return }
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        
        rootView.addSubview(backgroundView)
        rootView.addSubview(self)
        backgroundView.snp.makeConstraints { (make) in
            make.edges.equalTo(rootView)
        }
        let height = getHieght()
        snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(min(screenWidth, screenHeight))
            make.height.equalTo(height)
            make.bottom.equalTo(height)
        }
        
        addSubview(backView)
        backView.addSubview(closeBar)
        backView.addSubview(lineView)
        backView.addSubview(titleLabel)
        backView.addSubview(plaformView)
        backView.addSubview(promptLabel)
        backView.addSubview(conformBtn)
        
        backView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        closeBar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(16)
        }
        lineView.snp.makeConstraints { make in
            make.center.equalTo(closeBar)
            make.height.equalTo(4)
            make.width.equalTo(36)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(closeBar.snp.bottom).offset(18)
        }
        plaformView.snp.makeConstraints { make in
            make.left.equalTo(26)
            make.right.equalTo(-26)
            make.top.equalTo(titleLabel.snp.bottom).offset(30)
            make.height.equalTo(62)
        }
        promptLabel.snp.makeConstraints { make in
            make.left.right.equalTo(plaformView)
            make.top.equalTo(plaformView.snp.bottom).offset(26)

        }
        conformBtn.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.right.equalTo(-22)
            make.bottom.equalTo(-(iPhoneX ? Size.safeAreaBottomGap:20))
            make.height.equalTo(CGFloat.app_btnHeight)
        }
        
        self.rootView.layoutIfNeeded()
        
        plaformView.isShowTopLineView = false

        closeBar.addTarget(self, action: #selector(hideAction), for: .touchUpInside)
        conformBtn.addTarget(self, action: #selector(confromBtnAction))

    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private lazy var backView: UIView = {
        let backView = UIView()
        backView.backgroundColor = UIColor.white
        return backView
    }()
    private lazy var closeBar = AppCustomButton()
    private lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor(hex: 0x6E6E6E).withAlphaComponent(0.4)
        lineView.isUserInteractionEnabled = false
        return lineView
    }()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = kSetPingFangBlod(16)
        titleLabel.textAlignment = .center
        return titleLabel
    }()
    private lazy var plaformView = WithdrawPlatformView(icon: platformType == .wechat ? "invite_wechat":"invite_ali", name: platformType == .wechat ? "微信提现".localized:"支付宝提现".localized, detail: kUserManager.userModel.wxName)
    private lazy var promptLabel: UILabel = {
        let promptLabel = UILabel()
        promptLabel.font = kSetPingFangMedium(14)
        promptLabel.textColor = UIColor.hex(hexString: "#D39C68")
        promptLabel.numberOfLines = 0
        return promptLabel
    }()
    private lazy var conformBtn: GradientButton = {
        let conformBtn = GradientButton()
        conformBtn.gradientColors = UIColor.app_themeGradientColors
        conformBtn.setFont(kSetPingFangBlod(16))
        conformBtn.setTitle("解除支付宝绑定".localized)
        return conformBtn
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension UnBindPlatformBottomAlertView {
    
    func show() {
        
        let tapGR = UITapGestureRecognizer.init(target: self, action: #selector(hideAction))
        tapGR.delegate = self
        backgroundView.addGestureRecognizer(tapGR)
        
        let panGR = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction(_:)))
        panGR.delegate = self
        addGestureRecognizer(panGR)
        
        UIView.animate(withDuration: 0.2, animations: {
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            self.snp.updateConstraints { make in
                make.bottom.equalTo(0)
            }
            self.rootView.layoutIfNeeded()
        })

    }
    
    @objc private func hideAction() {
        
        endEditing(true)
        
        hide()
    }
    
    private func hide(completion: (() -> Void)? = nil) {
        
        UIView.animate(withDuration: 0.2, animations: {
            self.snp.updateConstraints { make in
                make.bottom.equalTo(self.getHieght())
            }
            self.rootView.layoutIfNeeded()
        }) { finished in
            guard finished else { return }
            self.removeFromSuperview()
            self.backgroundView.removeFromSuperview()
        }
        
    }
    
    static func checkHideView() {
        guard let rootView = UIApplication.shared.keyWindow else { return }
        let subViews = rootView.subviews.filter({ $0.isKind(of: UnBindPlatformBottomAlertView.self) })
        if subViews.count > 0 {
            _ = subViews.map { ($0 as! UnBindPlatformBottomAlertView).hideAction() }
        }
    }
        
}

extension UnBindPlatformBottomAlertView: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    @objc func panGestureRecognizerAction(_ panGR: UIPanGestureRecognizer) {
        
        let position = panGR.location(in: rootView)
        var scale = position.y - panPositionY
        
        if panGR.state == .began {
            panPositionY = position.y
        } else if panGR.state == .changed {
            if scale < 0 {
                scale = 0
            }
            
            snp.updateConstraints { make in
                make.bottom.equalTo(scale)
            }
            layoutIfNeeded()
        } else if panGR.state == .ended {
            if scale > 40 {
                hideAction()
            } else {
                snp.updateConstraints { make in
                    make.bottom.equalTo(0)
                }
            }
        }
        
    }
    
}


